<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/2
 * Time: 10:48
 */


namespace Api\Controller;
use Think\Controller;

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class IndexController extends Controller {
    public $wechat;
    public function __construct()
    {
        parent::__construct();
        $this->wechat=M('wgzh')->find();
    }

    public function index(){
        $this->display();
    }

    //个人中心
    public function member(){
        //获取微信信息，要存入数据库，显示相关信息到页面
        //1.得到code
        $redurl=urlencode("http://video.czbke.com/index.php/Api/Index/user");
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->wechat['appid']}&redirect_uri=$redurl&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

        header("Location:$url");
//        $this->display();
    }

    //授权登录方法
    public function user(){
        //判断是否登录
        if($_SESSION['member']){
            $this->assign('list',$_SESSION['member']);
            $this->display();
            exit;
        }
        //1.得到access_token和openID
        $code=$_GET['code'];
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->wechat['appid']}&secret={$this->wechat['secret']}&code=$code&grant_type=authorization_code";
        $arr=file_get_contents($url);
        $arr=json_decode($arr,true);

        $model=M('wuser');
        $list=$model->where("openid = '{$arr['openid']}'")->find();
        if(empty($list)){
            //2.获取用户详细信息
            $url="https://api.weixin.qq.com/sns/userinfo?access_token={$arr['access_token']}&openid={$arr['openid']}&lang=zh_CN";
            $user=file_get_contents($url);
            $user=json_decode($user,true);
            if($user['openid']){
                //存储数据
                $list=array();
                $list['openid']=$user['openid'];
                $list['nickname']=$user['nickname'];
                $list['sex']=$user['sex']==1?'男':"女";
                $list['city']=$user['city'];
                $list['province']=$user['province'];
                $list['headimgurl']=$user['headimgurl'];

                if(!$model->add($list)){
                    exit('系统错误');
                }
            }else{
                exit('系统错误');
            }
        }

        $_SESSION['member']=$list;

        //3.调用页面显示数据
        $this->assign('list',$_SESSION['member']);
        $this->display();
    }


    //微信通知地址
    public function resMsg(){
        $echoStr = $_GET["echostr"]; //验证参数
        if($echoStr){
            if($this->checkSignature($this->wechat['token'])){
                echo $echoStr;
                exit;
            }
        }else{
            $this->responseMsg();
        }
    }

    //消息回复接口---实现消息回复
    public function responseMsg()
    {
        //get post data, May be due to the different environments
        //功能与post相同，专门用于接收XML 数据
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

//		file_put_contents('./obj.txt',$postStr);
        //extract post data
        if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            //解析XML 时不解析实体，防止xxe 攻击
            libxml_disable_entity_loader(true);
            //把xml数据转化为simplexml模型对象
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            //得到发送用户的openID，openID是唯一的，可以当做用户id使用
            $this->fromUsername = $postObj->FromUserName;
            //得到微信公众号的id，平台的id
            $this->toUsername = $postObj->ToUserName;
            /*****定义消息类******/
            $MsgType=$postObj->MsgType;
            if($MsgType=='text'){
                //文本消息
                //得到用户输入的内容
                $keyword = trim($postObj->Content);

                //匹配关键字，如果根据类型返回对应的消息
               $arr=M('wgjz')->where("keyword = '$keyword' and stat=1")->find();
               if($arr['type']=='1'){
                   //回复文本消息
                   //定义XML 数据
                   $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
                   //定义时间戳
                   $time = time();
                   $msgType='text';
                   $contentStr=$arr['text'];
                   //格式化字符串得到最终的回复数据
                   $resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
               }
               else{
                   //回复图文消息
                   $textTpl="<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <ArticleCount>%s</ArticleCount>
                                <Articles>
                                    %s
                                </Articles>
                            </xml>";
                   $time=time();
                   $msgType='news';
                   $list=json_decode($arr['text'],true); //得到图文数据
                   $cou=count($list);
                   //拼接图文内容
                   $str='';
                   foreach ($list as $v){
                       $s1="<item>
                                <Title><![CDATA[%s]]></Title> 
                                <Description><![CDATA[%s]]></Description>
                                <PicUrl><![CDATA[%s]]></PicUrl>
                                <Url><![CDATA[%s]]></Url>
                            </item>";

                       $str.=sprintf($s1,$v['Title'],$v['Description'],'http://video.czbke.com'.$v['Url'],$v['PicUrl']);
                   }
                   $resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, $time, $msgType,$cou,$str);
//                   file_put_contents('./obj.txt',$resultStr);
                   echo $resultStr;
               }


            }
        }
        else {
            echo "";
            exit;
        }
    }

    //验证token
    private function checkSignature($token)
    {
        // you must define TOKEN by yourself
        if (!$token) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = $token;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}